﻿
using System.Collections;
using System.Collections.Generic;

public abstract class NetMessageHandler
{
    protected abstract ISerialize NewData();

    ISerialize m_Data;
    ISerialize data
    {
        get
        {
            if (m_Data == null)
                m_Data = NewData();

            return m_Data;
        }
    }

    protected MessagePacket m_MessageReceived;

    public void Excuate(Remote client, MessagePacket _clientReqMsg)
    {
        m_MessageReceived = _clientReqMsg;
        m_Data = NewData();

        try
        {
            if (data != null)
                data.Read(_clientReqMsg.data);
        }
        catch (System.Exception e)
        {
            GameDebug.LogException(e);
        }
        
        Execute(client,data);
    }

    public abstract void Execute(Remote client, ISerialize data);

    protected virtual void OnSend() { }

    protected void SendResponse(Remote client,string key,int seq,byte[] data)
    {
        OnSend();

        SendNetMsg(client, key, seq, data);
    }

   
    protected void SendResponse(Remote[] clients, string key, int seq, byte[] data)
    {
        OnSend();

        foreach (var client in clients)
        {
            SendNetMsg(client, key, seq, data);
        }
    }

    void SendNetMsg(Remote client, string key, int seq, byte[] data)
    {
        MessagePacket sendMsg = new MessagePacket();
        sendMsg.key = key;
        sendMsg.seq = seq;
        sendMsg.data = data;
        sendMsg.type = MessagePacketType.Response;

        client.Send(sendMsg);
    }


}


//public abstract class NetSendResponse: NetMessageHandler
//{

//    public NetSendToServer request;

//    public override void Execute(TCPRemote client, ISerialize data)
//    {
//        request?.onResponse?.Invoke(this); 
//    }
//}